#include <Keypad.h>

#include <TFT_eSPI.h>
#define beep_pin 16

// 显示屏对象
// extern TFT_eSPI tft = TFT_eSPI(240*320);
extern char pad_key;   // 读取到的字符

extern const byte ROWS = 4; //four rows
extern const byte COLS = 4; //four columns
extern char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

extern char passwd[4][5] = {
    {'2', '8', '7', '6', 'A'},
    {'2', '8', '7', '7', 'B'},
    {'2', '8', '7', '8', 'C'},
    {'2', '8', '7', '9', 'D'}
};

byte rowPins[ROWS] = {32,33,25,26}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {27,14,12,13};  // connect to the column pinouts of the keypad


//Create an object of keypad
extern Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
  
// 存储输入  
extern char input[5] = {0};
extern int idx = -1;


// 用于屏幕初始化或更新
// extern void tft_init(){
//   tft.init();
//   tft.setRotation(0);
//   tft.fillScreen(TFT_WHITE);
// }



extern void clear(){
  spr.setColorDepth(8);
  spr.createSprite(240, 180);                           // 创建一个像素240*180的画布
  spr.fillSprite(TFT_WHITE);
  spr.pushSprite(0, 80);                                      // 画布推到（0，80）显示
}


// 判断密码是否正确
extern int authenticated(){
  int i = 0;
  switch(input[4]){
    case 'A':
      for (i = 0; i < 4;i++){
        if(input[i]!=passwd[0][i]) 
          return 0;
      }
      Serial.print("A床开门：");
      return 1;
      break;

    case 'B':
      for (i = 0; i < 4; i++)
      {
        if (input[i] != passwd[1][i])
          return 0;
      }
      Serial.print("B床开门：");
      return 1;
      break;

    case 'C':
      for (i = 0; i < 4; i++)
      {
        if (input[i] != passwd[2][i])
          return 0;
      }
      Serial.print("C床开门：");
      return 1;
      break;

    case 'D':
      for (i = 0; i < 4; i++)
      {
        if (input[i] != passwd[3][i])
          return 0;
      }
      Serial.print("D床开门：");
      return 1;
      break;

    default:
      return 0;
  }
}



// 蜂鸣器根据是否要门发声
extern void Beep(bool opened){
  char g_i = 0;
  if(opened){
    int cnt = 0;
    while(cnt<1500){
      g_i = !g_i;     // 电平翻转
      digitalWrite(beep_pin, g_i);    // 引脚输出电平
      delayMicroseconds(250);
      cnt ++;
    }
  }

  else{
    int cnt = 0;
    while(cnt<902){
      g_i = !g_i;
      if(cnt%100==0)    // 中断声
        delay(100);
      digitalWrite(beep_pin, g_i);
      delayMicroseconds(250);
      cnt ++;
    }
  }
}
